<!--
 * @Author: 贾博林 11457230+jabolin@user.noreply.gitee.com
 * @Date: 2022-10-21 15:15:44
 * @LastEditors: 贾博林 11457230+jabolin@user.noreply.gitee.com
 * @LastEditTime: 2022-10-26 20:47:41
 * @FilePath: \v-shop\code\src\views\roles.vue
 * @Description: rloes页面
-->
<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <br />

    <!-- 卡片 -->
    <el-card>
      <el-button type="primary" @click="add">添加角色</el-button>
      <br />
      <br />
      <!-- 表格 -->
      <el-table :data="roles" border style="width: 100%">
        <el-table-column>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <!-- <pre>{{scope.row}}</pre> -->
              <el-row
                :class="[i1 === 0 ? '' : 'bdtop', 'vcenter']"
                v-for="(item1, i1) in scope.row.children"
                :key="item1.id"
              >
                <!-- 一级 -->
                <el-col :span="5">
                  <el-tag closable @close="shanChu(scope.row, item1.id)">
                    {{ item1.authName }}</el-tag
                  >
                </el-col>
                <!-- 二级和三级 -->
                <el-col :span="19">
                  <el-row
                    :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                    v-for="(item2, i2) in item1.children"
                    :key="item2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        type="success"
                        closable
                        @close="shanChu(scope.row, item2.id)"
                        >{{ item2.authName }}
                      </el-tag>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        type="warning"
                        closable
                        @close="shanChu(scope.row, item3.id)"
                      >
                        {{ item3.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
            >
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope.$index, scope.row)"
            >
            </el-button>
            <el-button
              type="warning"
              icon="el-icon-star-off"
              size="mini"
              @click="handleEdit2(scope.$index, scope.row)"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加模态框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >添加</el-button
        >
      </div>
    </el-dialog>

    <!-- 修改模态框 -->
    <el-dialog title="编辑用户" :visible.sync="dialogFormVisible2">
      <el-form
        :model="ruleForm2"
        :rules="rules2"
        ref="ruleForm2"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm2.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm2.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm2('ruleForm2')"
          >修改</el-button
        >
      </div>
    </el-dialog>

    <!-- 分配权限模态框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogFormVisible3"
      @close="clearDefaultKeys"
    >
      <el-tree
        :data="rightTree"
        :props="treesProps"
        show-checkbox
        default-expand-all
        ref="treeData"
        node-key="id"
        :default-expanded-keys="defaultKeys"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm3">添加权限</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  roles,
  roles_tjjs,
  roles_xgjs,
  roles_scjs,
  shanchu,
  rolesList,
  addRoleRights,
} from "../http/roles/api";
export default {
  name: "roles",
  data() {
    return {
      roles: [],
      rightTree: [],
      // 默认勾选数组
      defaultKeys: [],
      roleID: "", //打开弹框的时候拿到该角色id
      // 靶子对象
      treesProps: {
        label: "authName",
        children: "children",
      },

      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      // 添加
      ruleForm: {
        roleName: "",
        roleDesc: "",
        id: "",
      },

      // 修改
      ruleForm2: {
        roleName: "",
        roleDesc: "",
        id: "",
      },

      // 分配权限
      ruleForm3: {
        roleName: "",
        roleDesc: "",
      },

      // 添加验证
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },

      // 修改验证
      rules2: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },

      // 分配权限
      rules3: {},
    };
  },

  components: {},

  computed: {},

  // 钩子函数
  mounted() {
    this.getdata();
  },

  // 方法
  methods: {
    // 分配权限
    async handleEdit2(role) {
      this.roleID = role.id;
      this.dialogFormVisible3 = true;
      // 渲染 树状图 数据
      const { data: res } = await rolesList();

      if (res.meta.status !== 200) {
        return this.$message.error("获取用户权限列表失败");
      }
      console.log(res);
      this.rightTree = res.data;
    },

    // 添加树状图 标签数据
    async submitForm3() {
      let key = [
        ...this.$refs.treeData.getCheckedKeys(),
        ...this.$refs.treeData.getHalfCheckedKeys(),
      ];
      let idStr = key.join(",");
      // console.log(key, '数组');
      // console.log(idStr, '字符串');
      let { data: res } = await addRoleRights(this.roleID, { rids: idStr });
      // if (res.meta.status !== 200) {
      //   return this.$message.error("分配权限失败");
      // }
      this.$message.success("分配权限成功!");
      this.getdata();
      this.dialogFormVisible3 = false;
    },

    // 递归遍历三级节点 ，如果没有chiledren就是三级节点，渲染数组
    getleafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getleafKeys(item, arr);
      });
      console.log(arr, "keys");
    },

    //关闭弹框 清除默认选中
    clearDefaultKeys() {
      this.defaultKeys = [];
    },

    //  编辑
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogFormVisible2 = true;
      this.ruleForm2 = row;
    },

    // 删除
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          roles_scjs(row).then((res) => {
            // console.log(res, "删除");
            this.getdata();
            this.$message({
              type: "success",
              message: res.data.meta.msg,
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 点击出现添加模态框
    add() {
      this.dialogFormVisible = true;
    },

    // 渲染
    getdata() {
      roles().then((res) => {
        console.log(res, "渲染");
        this.roles = res.data.data;
      });
    },

    // 添加
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          roles_tjjs(this.ruleForm).then((res) => {
            // console.log(res,'tianjia');
            this.$message({
              type: "success",
              message: res.data.meta.msg,
            });
            this.getdata();
            this.dialogFormVisible = false;
            // 清空添加
            this.ruleForm = {
              roleName: "",
              roleDesc: "",
            };
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 修改
    submitForm2(ruleFrom2) {
      this.$refs[ruleFrom2].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm2);
          roles_xgjs(this.ruleForm2).then((res) => {
            console.log(res, "修改");
            this.$message({
              type: "success",
              message: res.data.meta.msg,
            });
            this.dialogFormVisible2 = false;
            this.getdata();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 删除标签
    shanChu(row, rightId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await shanchu(row.id, rightId);
          console.log(res, "删除标签");
          row.children = res.data;
          this.$message({
            type: "success",
            message: res.meta.msg,
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  watch: {},
  mixins: [],
};
</script>
<style  scoped>
.el-tag {
  margin: 10px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
  padding: 6px;
}
</style>